import requests
import time
from frame_work.logger import Logger
from frame_work.util import check_tid, change_user_account_status, assert_result_dict, get_sql_info, update_sql_info
from frame_work import menu_list
from frame_work.setting import *
from frame_work.yaml_file import YAML

logger = Logger(__name__).get_logger()

# http://sksystem.sk.com/tasktimer/try_auto_online/40001661 定时器执行上线活动

class Timer(object):

    def __init__(self, uname, tid=None):
        self.tid = tid
        self.uname = uname
        self.yaml = YAML(os.path.join(base_Dir, 'data', 'data.yaml'))

    @staticmethod
    def get_server_current_time():
        """
        获取数据库端时间
        :return:时间戳
        """
        statement = """SELECT NOW()"""
        params = ()
        value = get_sql_info(statement, params, meta={
            "info": "查询数据库服务器时间"
        })
        server_time = str(value[0].get("NOW()"))
        timeArray = time.strptime(server_time, "%Y-%m-%d %H:%M:%S")
        server_time_stamp = int(time.mktime(timeArray))
        return server_time_stamp

    def get_jid(self, flag):
        """
        获取sk_join表jid值
        :param flag:
        :return:
        """
        statement = ''
        if flag == 1:
            statement = """SELECT jid from sk_join WHERE trade_no_state=1 and buyer_uname = %s and tid = %s"""
        elif flag == 2:
            statement = """SELECT jid from sk_join WHERE report_state=1 and buyer_uname = %s and tid = %s"""
        elif flag == 3:
            statement = """SELECT jid from sk_join WHERE (trade_no_state=4 or report_state=4) and buyer_uname = %s and tid = %s"""
        elif flag == 4:
            statement = """SELECT jid from sk_join WHERE report_state=2 and buyer_uname = %s and tid = %s"""
        elif flag == 5:
            statement = """SELECT jid from sk_join WHERE report_state=3 and buyer_uname = %s and tid = %s"""
        elif flag == 6:
            statement = """SELECT jid from sk_join WHERE (trade_no_state=4 or report_state = 4) and buyer_uname = %s and tid = %s"""
        elif flag == 7:
            statement = """SELECT jid from sk_join WHERE  report_state = 2 and buyer_uname = %s and tid = %s"""
        elif flag == 8:
            statement = """SELECT jid from sk_join WHERE  report_state = 1 and buyer_uname = %s and tid = %s"""
        params = (self.uname, self.tid,)
        value = get_sql_info(statement, params, meta={
            "info": "查询参与jid"
        })
        return value[0]

    def join_wait_no(self):
        """
        试客逾期未提交单号，自动终止 type = 100;
        :return:
        """
        jid_obj = self.get_jid(flag=1)
        if jid_obj:
            # 将时间改到当前服务器时间-10秒
            auto_time_wait_no = Timer.get_server_current_time() - 10
            statement = """update sk_join set auto_time_wait_no = %s WHERE state=1 and buyer_uname = %s and tid = %s"""
            params = (auto_time_wait_no, self.uname, self.tid)
            update_sql_info(statement, params, meta={
                            "info": "执行试客逾期未提交单号，自动终止"
                            })
            join_wait_no_url = self.yaml.get_data(
                'join_wait_no')['url'] + '/' + str(jid_obj.get("jid"))
            response_data = requests.get(join_wait_no_url).text
            response_data = response_data.encode(
                'utf-8').decode("unicode_escape")
            logger.debug(response_data)
            assert_result_dict(response_data, '试客逾期未提交单号，自动终止')
        else:
            logger.debug("参与状态不对，没有该记录...")

    def join_wait_report(self):
        """
        试客逾期未提交报告，自动终止 type = 101;
        :return:
        """
        jid_obj = self.get_jid(flag=2)
        if jid_obj:
            # 将时间改到当前服务器时间-10秒
            auto_time_wait_report = Timer.get_server_current_time() - 10
            statement = """update sk_join set auto_time_wait_report = %s WHERE state=2 and buyer_uname = %s and tid = %s"""
            params = (auto_time_wait_report, self.uname, self.tid)
            update_sql_info(statement, params, meta={
                            "info": "执行试客逾期未提交报告，自动终止"
                            })
            join_wait_report_url = self.yaml.get_data('join_wait_report')[
                'url'] + '/' + str(jid_obj.get("jid"))
            response_data = requests.get(join_wait_report_url).text
            response_data = response_data.encode(
                'utf-8').decode("unicode_escape")
            logger.debug(response_data)
            assert_result_dict(response_data, '试客逾期未提交报告，自动终止')
        else:
            logger.debug("参与状态不对，没有该记录...")

    def join_wait_modify(self):
        """
        试客逾期X天未修改单号或报告，自动终止 type = 102;
        :return:
        """
        jid_obj = self.get_jid(flag=3)
        if jid_obj:
            # 将时间改到当前服务器时间-10秒
            auto_time_wait_modify = Timer.get_server_current_time() - 10
            statement = """update sk_join set auto_time_wait_modify = %s WHERE state=5 and buyer_uname = %s and tid = %s"""
            params = (auto_time_wait_modify, self.uname, self.tid)
            update_sql_info(statement, params, meta={
                            "info": "执行试客逾期X天未修改单号或报告，自动终止"
                            })
            join_wait_modify_url = self.yaml.get_data('join_wait_modify')[
                'url'] + '/' + str(jid_obj.get("jid"))
            response_data = requests.get(join_wait_modify_url).text
            response_data = response_data.encode(
                'utf-8').decode("unicode_escape")
            logger.debug(response_data)
            assert_result_dict(response_data, '试客逾期未修改单号或报告，自动终止')
        else:
            logger.debug("参与状态不对，没有该记录...")

    def join_wait_check(self):
        """
        商家逾期未审核报告，审核时间到期自动试用完成，type = 103;
        :return:
        """
        jid_obj = self.get_jid(flag=4)
        if jid_obj:
            # 将时间改到当前服务器时间-10秒
            auto_time_wait_check = Timer.get_server_current_time() - 10
            statement = """update sk_join set auto_time_wait_check = %s WHERE state=3 and buyer_uname = %s and tid = %s"""
            params = (auto_time_wait_check, self.uname, self.tid)
            update_sql_info(statement, params, meta={
                            "info": "执行商家逾期未审核报告，审核时间到期自动试用完成"
                            })
            join_wait_check_url = self.yaml.get_data('join_wait_check')[
                'url'] + '/' + str(jid_obj.get("jid"))
            response_data = requests.get(join_wait_check_url).text
            response_data = response_data.encode(
                'utf-8').decode("unicode_escape")
            logger.debug(response_data)
            assert_result_dict(response_data, '商家逾期未审核报告，审核时间到期自动试用完成')
        else:
            logger.debug("参与状态不对，没有该记录...")

    def join_wait_rebate(self):
        """
        商家已审核通过报告未返款，时间到期自动返款给试客 type = 104;
        :return:
        """
        jid_obj = self.get_jid(flag=5)
        if jid_obj:
            # 将时间改到当前服务器时间-10秒
            auto_time_wait_check = Timer.get_server_current_time() - 10
            statement = """update sk_join set auto_time_wait_check = %s WHERE state=4 and buyer_uname = %s and tid = %s"""
            params = (auto_time_wait_check, self.uname, self.tid)
            update_sql_info(statement, params, meta={
                            "info": "执行商家已审核通过报告未返款，时间到期自动返款给试客"
                            })
            join_wait_rebate_url = self.yaml.get_data('join_wait_rebate')[
                'url'] + '/' + str(jid_obj.get("jid"))
            response_data = requests.get(join_wait_rebate_url).text
            response_data = response_data.encode(
                'utf-8').decode("unicode_escape")
            logger.debug(response_data)
            assert_result_dict(response_data, '商家已审核通过报告未返款，时间到期自动返款给试客')
        else:
            logger.debug("参与状态不对，没有该记录...")

    def join_message_wait_report(self):
        """
        逾期未提交报告，自动终止 - 逾期前2天发送试客消息提醒 type = 150;
        :return:
        """
        jid_obj = self.get_jid(flag=2)
        if jid_obj:
            join_message_wait_report_url = self.yaml.get_data('join_message_wait_report')[
                'url'] + '/' + str(jid_obj.get("jid"))
            response_data = requests.get(join_message_wait_report_url).text
            response_data = response_data.encode(
                'utf-8').decode("unicode_escape")
            logger.debug(response_data)
            assert_result_dict(response_data, '逾期未提交报告，自动终止')
        else:
            logger.debug("参与状态不对，不是待提交报告状态...")

    def join_message_wait_modify(self):
        """
        逾期X天未修改单号或报告，自动终止 - 逾期前2天发送试客消息提醒 type = 151;
        :return:
        """
        jid_obj = self.get_jid(flag=3)
        if jid_obj:
            join_message_wait_modify_url = self.yaml.get_data('join_message_wait_modify')[
                'url'] + '/' + str(jid_obj.get("jid"))
            response_data = requests.get(join_message_wait_modify_url).text
            response_data = response_data.encode(
                'utf-8').decode("unicode_escape")
            logger.debug(response_data)
            assert_result_dict(response_data, '逾期未修改单号或报告，自动终止')
        else:
            logger.debug("参与状态不对，不是审核未通过(包括订单号/报告未通过)状态...")

    def join_message_wait_check(self):
        """
        逾期X天未审核报告，自动审核通过 - 逾期前2天发送商家消息提醒 type = 152;
        :return:
        """
        jid_obj = self.get_jid(flag=4)
        if jid_obj:
            join_message_wait_check_url = self.yaml.get_data('join_message_wait_check')[
                'url'] + '/' + str(jid_obj.get("jid"))
            response_data = requests.get(join_message_wait_check_url).text
            response_data = response_data.encode(
                'utf-8').decode("unicode_escape")
            logger.debug(response_data)
            assert_result_dict(response_data, '逾期未审核报告，自动审核通过')
        else:
            logger.debug("参与状态不对，不是待审核状态...")

    def auto_unblock_user(self):
        """
        自动解除被屏蔽用户 type = 300;
        :return:
        """
        statement = """SELECT uid from sk_user where uname = %s"""
        params = (self.uname,)
        value = get_sql_info(statement, params, meta={
            "info": "查询用户uid"
        })
        uid = value[0].get("uid")
        if uid:
            auto_unblock_user_url = self.yaml.get_data('auto_unblock_user')[
                'url'] + '/' + str(uid)
            response_data = requests.get(auto_unblock_user_url).text
            response_data = response_data.encode(
                'utf-8').decode("unicode_escape")
            logger.debug(response_data)
            assert_result_dict(response_data, '自动解除被屏蔽用户')
        else:
            logger.debug("非法用户...")

    def auto_unban_comment(self):
        """
        达人秀自动解除禁言 type = 400;
        :param uname:
        :return:
        """
        statement = """SELECT uid from sk_user where uname = %s"""
        params = (self.uname,)
        value = get_sql_info(statement, params, meta={
            "info": "查询用户uid"
        })
        uid = value[0].get("uid")
        if uid:
            auto_unban_comment_url = self.yaml.get_data('auto_unblock_user')[
                'url'] + '/' + str(uid)
            response_data = requests.get(auto_unban_comment_url).text
            response_data = response_data.encode(
                'utf-8').decode("unicode_escape")
            logger.debug(response_data)
            assert_result_dict(response_data, '达人秀自动解除禁言')
        else:
            logger.debug("非法用户...")

    def try_message_offline_wait_check(self, uname, tid):
        # TODO 待完成活动结束前24小时还有待审批的试用资格发送提醒功能
        """
        活动结束前24小时还有待审批的试用资格，发送提醒给商家审批试客资格 type = 2;
        :param uname:
        :param tid:
        :return:
        """
        pass

    def try_offline_wait_check(self, tid):
        # TODO 待完成活动结束后48小时还有待审批的试用资格功能
        """
        活动结束后48小时还有待审批的试用资格，自动审批 type = 3;
        :param tid:
        :return:
        """
        pass

    def seller_vip_overdue(self, uname):
        # TODO 待完成商家VIP服务到期功能
        # 商家vip服务到期
        # import datetime
        # from dateutil.relativedelta import relativedelta
        #
        # month_diff = []
        # period_time = tuple()
        # statement = """
        # SELECT
        #     TIMESTAMPDIFF(MONTH,a.start_time,a.end_time) +1
        # FROM
        #     sk_user_seller_upgrade a
        # WHERE
        #     a.uname = %s
        #            """
        # params = (uname,)
        # value = self.sql.exec_query(statement,params)
        # for i in value:
        #     month_diff.append(i[0])
        # time_stamp = self.get_server_current_time() - 43200
        # last_due_vip = time.strftime("%Y-%m-%d",time.localtime(time_stamp))
        # aa = len(value)
        # while aa:
        #     sdate  = datetime.datetime.strptime(last_due_vip,'%Y-%m-%d')
        #     ms = month_diff[3]
        #     start_time = sdate-relativedelta(months=ms)
        #
        pass

    def assert_result(self, prompt, response):
        """
        判断结果
        :param promote:
        :return:
        """
        if prompt in response:
            logger.info('执行完毕!')
            return True
        else:
            logger.info('执行失败!')
            return False


def main():
    while True:
        # 显示功能菜单
        menu_list.timer_task_menu()
        # 选择
        choise = input("请输入您的选择: ")
        if choise in ('q', 'Q'):
            break
        try:
            if choise not in ('9', '10'):
                tid = int(input(u'请输入活动tid: '))
                status = check_tid(tid)
                if not status:
                    raise Exception("活动tid不存在try表，请核实后在重新输入")
        except Exception as e:
            logger.error("reszon => %s" % e)
        else:
            buyer_name = input(u'请输入试客名称: ')
            user_status = change_user_account_status(buyer_name)
            if not user_status:
                break
            if choise == '1':
                timer = Timer(buyer_name, tid)
                timer.join_wait_no()
            elif choise == '2':
                timer = Timer(buyer_name, tid)
                timer.join_wait_report()
            elif choise == '3':
                timer = Timer(buyer_name, tid)
                timer.join_wait_modify()
            elif choise == '4':
                timer = Timer(buyer_name, tid)
                timer.join_wait_check()
            elif choise == '5':
                timer = Timer(buyer_name, tid)
                timer.join_wait_rebate()
            elif choise == '6':
                timer = Timer(buyer_name, tid)
                timer.join_message_wait_report()
            elif choise == '7':
                timer = Timer(buyer_name, tid)
                timer.join_message_wait_modify()
            elif choise == '8':
                timer = Timer(buyer_name, tid)
                timer.join_message_wait_check()
            elif choise == '9':
                timer = Timer(buyer_name)
                timer.auto_unblock_user()
            elif choise == '10':
                timer = Timer(buyer_name)
                timer.auto_unban_comment()
            # elif choise == '11':
            #     timer.try_message_offline_wait_check(buyer_name,tid)
            # elif choise == '12':
            #     timer.try_offline_wait_check(tid)
            # elif choise == '13':
            #     timer.try_offline_wait_check(tid)
            else:
                logger.info("没有对应的选项,请按选项输入...")
                break


if __name__ == "__main__":
    # a = Timer()
    # print(a.get_server_current_time())
    main()
